package com.yihu.wlyy.web.doctor.intervene;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.patient.PatientInspectionSuggest;
import com.yihu.wlyy.entity.patient.PatientSelfInspection;
import com.yihu.wlyy.entity.patient.PatientSelfInspectionItem;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.app.intervene.PatientInspectionService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.MessageType;
import com.yihu.wlyy.web.BaseController;

/**
 * 医生干预控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/intervene")
public class DoctorInterveneController extends BaseController {

	@Autowired
	private DoctorService doctorService;
	@Autowired
	private PatientDeviceService patientDeviceService;
	@Autowired
	private PatientInspectionService patientInspectionService;

	/**
	 * 患者可用设备查询接口
	 * @param patient
	 * @return
	 */
	@RequestMapping(value = "devices")
	@ResponseBody
	public String devices(String patient) {
		try {
			JSONArray array = new JSONArray();
			Iterator<PatientDevice> iterator = patientDeviceService.findPatientHave(patient);
			while (iterator != null && iterator.hasNext()) {
				PatientDevice pd = iterator.next();
				if (pd == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 设置设备标识
				json.put("code", pd.getDeviceId());
				// 设置设备名称
				json.put("name", pd.getDeviceName());
				array.put(json);
			}
			return write(200, "查询成功", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 添加患者自查接口
	 * @param type 咨询类型：1三师咨询（即时咨询），2视频咨询
	 * @param consult 咨询标识
	 * @param patient 患者标识
	 * @param devices 建议设备信息
	 * @return
	 */
	@RequestMapping(value = "self_exam")
	@ResponseBody
	public String selfExam(@RequestParam(required = false) Integer type, @RequestParam(required = false) String consult, String patient, String devices) {
		try {
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			if (type == null) {
				type = 0;
			}
			// 生成自查对象
			PatientSelfInspection inspection = new PatientSelfInspection();
			// 设置自查标识
			inspection.setCode(patientInspectionService.getCode());
			// 设置咨询标识
			inspection.setConsult(consult);
			inspection.setCzrq(new Date());
			// 设置医生标识
			inspection.setDoctor(doctor.getCode());
			// 设置医生姓名
			inspection.setDoctorName(doctor.getName());
			// 设置患者标识
			inspection.setPatient(patient);
			// 设置咨询类型：1三师咨询（即时咨询），2视频咨询
			inspection.setType(type);
			inspection.setDel("1");
			// 生成自查建议项
			String title = "";
			List<PatientSelfInspectionItem> items = new ArrayList<PatientSelfInspectionItem>();
			JSONArray array = new JSONArray(devices);
			for (int i = 0; i < array.length(); i++) {
				JSONObject json = array.getJSONObject(i);
				if (json == null) {
					continue;
				}
				PatientSelfInspectionItem item = new PatientSelfInspectionItem();
				// 设置自查项说明
				item.setContent(json.getString("content"));
				item.setCzrq(inspection.getCzrq());
				// 设置设备标识
				// item.setDevice(json.getString("device"));
				// 设置设备名称
				item.setDeviceName(json.getString("device_name"));
				// 设置自查标识
				item.setInspection(inspection.getCode());
				items.add(item);
				if (title.length() == 0) {
					title = json.getString("device_name");
				} else {
					title += "、" + json.getString("device_name");
				}
			}
			// 设置标题
			inspection.setTitle(title);
			if (items.isEmpty()) {
				return error(-1, "保存失败！");
			}
			// 保存到数据库
			patientInspectionService.save(inspection, items);
			// 推送消息给患者
			PushMsgTask.getInstance().put(patient, MessageType.MESSAGE_TYPE_PATIENT_SELF_INSPECTION.P_SI_01.name(), MessageType.MESSAGE_TYPE_PATIENT_SELF_INSPECTION.体测提醒.name(), MessageType.MESSAGE_TYPE_PATIENT_SELF_INSPECTION.您有新的体测提醒.name(), inspection.getCode());
			return success("保存成功");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}

	/**
	 * 添加检查建议接口
	 * @param type 咨询类型：1三师咨询（即时咨询），2视频咨询
	 * @param consult 咨询标识
	 * @param patient 患者标识
	 * @param suggest 检查建议
	 * @return
	 */
	@RequestMapping(value = "inspection")
	@ResponseBody
	public String inspection(int type, String consult, String patient, String suggest) {
		try {
			// 查询医生信息
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			PatientInspectionSuggest pis = new PatientInspectionSuggest();
			// 设置咨询标识
			pis.setConsult(consult);
			pis.setCzrq(new Date());
			// 设置医生标识
			pis.setDoctor(getUID());
			// 设置医生姓名
			pis.setDoctorName(doctor.getName());
			pis.setDel("1");
			// 设置患者标识
			pis.setPatient(patient);
			// 设置咨询类型：1三师咨询（即时咨询），2视频咨询
			pis.setType(type);
			// 设置建议内容
			pis.setContent(suggest);
			// 保存到数据库
			PatientInspectionSuggest temp = patientInspectionService.save(pis);
			// 推送消息给患者
			PushMsgTask.getInstance().put(patient, MessageType.MESSAGE_TYPE_PATIENT_INSPECTION_SUGGEST.P_IS_01.name(), MessageType.MESSAGE_TYPE_PATIENT_INSPECTION_SUGGEST.检查检验.name(), MessageType.MESSAGE_TYPE_PATIENT_INSPECTION_SUGGEST.您有新的检查检验建议.name(), String.valueOf(temp.getId()));
			return success("保存成功");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}

	/**
	 * 患者检查建议查询接口
	 * @param patient
	 * @param id
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "inspection_list")
	@ResponseBody
	public String inspection(String patient, long id, int pagesize) {
		try {
			Page<PatientInspectionSuggest> list = patientInspectionService.findPatientSuggestByDoctor(getUID(), patient, id, pagesize);
			JSONArray array = new JSONArray();
			if (list != null) {
				for (PatientInspectionSuggest suggest : list) {
					if (suggest == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", suggest.getId());
					json.put("content", suggest.getContent());
					json.put("czrq", DateUtil.dateToStrLong(suggest.getCzrq()));
					array.put(json);
				}
			}
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 查询指定患者的体测提醒
	 * @param patient
	 * @param id
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "self_exam_list")
	@ResponseBody
	public String selfExamList(String patient, long id, int pagesize) {
		try {
			Page<PatientSelfInspection> list = patientInspectionService.findPatientByDoctor(getUID(), patient, id, pagesize);
			JSONArray array = new JSONArray();
			if (list != null) {
				for (PatientSelfInspection psi : list) {
					if (psi == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", psi.getId());
					json.put("code", psi.getCode());
					json.put("title", psi.getTitle());
					json.put("type", psi.getType());
					json.put("czrq", DateUtil.dateToStrLong(psi.getCzrq()));
					array.put(json);
				}
			}
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 查询体检提醒信息
	 * @param inspection 提醒标识
	 * @return
	 */
	@RequestMapping(value = "self_exam_info")
	@ResponseBody
	public String selfExamInfo(String inspection) {
		try {
			List<PatientSelfInspectionItem> list = patientInspectionService.findSelfExamInfo(inspection);
			JSONArray array = new JSONArray();
			if (list != null) {
				for (PatientSelfInspectionItem psii : list) {
					if (psii == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 设备名称
					json.put("deviceName", psii.getDeviceName());
					// 提醒说明
					json.put("content", psii.getContent());
					array.put(json);
				}
			}
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

}
